//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
using System.Architecture;
using System.Windows;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
//using Prism.Desktop.Metro;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Microsoft.Practices.Prism.Regions.Behaviors
{
    /// <summary>
    /// Behavior that synchronizes the <see cref="IRegion.Context"/> property of a <see cref="IRegion"/> with 
    /// the control that hosts the Region. It does this by setting the <see cref="RegionManager.RegionContextProperty"/> 
    /// Dependency Property on the host control.
    /// 
    /// This behavior allows the usage of two way databinding of the RegionContext from XAML. 
    /// </summary>
    [ExportRegionBehavior("ViewStateAwareRegionBehavior")]
    public class ViewStateAwareRegionBehavior : RegionBehavior, IHostAwareRegionBehavior
    {
        private const string RegionContextPropertyName = "Context";
        private DependencyObject hostControl;

        /// <summary>
        /// Name that identifies the SyncRegionContextWithHostBehavior behavior in a collection of RegionsBehaviors. 
        /// </summary>
        public static readonly string BehaviorKey = "ViewStateAwareRegionBehavior";

        private ObservableObject<object> HostControlRegionContext
        {
            get
            {
                return RegionContext.GetObservableContext(this.hostControl);
            }
        }

        /// <summary>
        /// Gets or sets the <see cref="DependencyObject"/> that the <see cref="IRegion"/> is attached to.
        /// </summary>
        /// <value>
        /// A <see cref="DependencyObject"/> that the <see cref="IRegion"/> is attached to.
        /// This is usually a <see cref="FrameworkElement"/> that is part of the tree.
        /// </value>
        public DependencyObject HostControl
        {
            get
            {
                return hostControl;
            }
            set
            {
                if (IsAttached)
                {
                    throw new InvalidOperationException(ResourceHelper.HostControlCannotBeSetAfterAttach);
                }
                this.hostControl = value;
            }
        }

        /// <summary>
        /// Override this method to perform the logic after the behavior has been attached.
        /// </summary>
        protected override void OnAttach()
        {
            if (this.HostControl != null)
            {
                // Start listening to view state changes when there are controls interested in updates
                Window.Current.SizeChanged += this.WindowSizeChanged;
            }
        }

        private void WindowSizeChanged(object sender, WindowSizeChangedEventArgs e)
        {
            this.InvalidateVisualState();
        }

        /// <summary>
        /// Updates all controls that are listening for visual state changes with the correct
        /// visual state.
        /// </summary>
        /// <remarks>
        /// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
        /// signal that a different value may be returned even though the view state has not
        /// changed.
        /// </remarks>
        public void InvalidateVisualState()
        {
            if (this.HostControl != null)
            {

                string visualState = DetermineVisualState(ApplicationView.Value);
                VisualStateManager.GoToState((Control)HostControl, visualState, false);

                /*
                var candidateViews = from view in Region.Views
                                     where view != null
                                     let viewType = view.GetType()
                                     let viewMetadata = viewType.GetCustomAttribute<ExportViewAttribute>(false)
                                     where CompareViewStatesAllowance(viewMetadata.SupportedViewStates, ApplicationView.Value)
                                     select view;

                // deactivate views
                var viewsToBeDeactivated = Region.ActiveViews.Except(candidateViews).Intersect(Region.ActiveViews);
                if (viewsToBeDeactivated != null)
                    foreach(var iter in viewsToBeDeactivated)
                        Region.Deactivate(iter);

                if (candidateViews == null || candidateViews.Count() == 0)
                    return;

                if (Region is SingleActiveRegion)
                    Region.Activate(candidateViews.First());
                else
                    foreach (var view in candidateViews)
                        Region.Activate(view);
                */
                Region.ReloadContent();
                RegionManager.UpdateRegions();
            }
        }

        //private bool CompareViewStatesAllowance(ViewState supported, ApplicationViewState toBeChecked)
        //{
        //    if (supported.HasFlag(ViewState.Snapped) && toBeChecked == ApplicationViewState.Snapped)
        //        return true;

        //    if (supported.HasFlag(ViewState.Filled) && toBeChecked == ApplicationViewState.Filled)
        //        return true;

        //    if (supported.HasFlag(ViewState.FullScreenLandscape) && toBeChecked == ApplicationViewState.FullScreenLandscape)
        //        return true;

        //    if (supported.HasFlag(ViewState.FullScreenPortrait) && toBeChecked == ApplicationViewState.FullScreenPortrait)
        //        return true;

        //    if (supported == ViewState.AllStates)
        //        return true;

        //    return false;
        //}


        /// <summary>
        /// Translates <see cref="ApplicationViewState"/> values into strings for visual state
        /// management within the page.  The default implementation uses the names of enum values.
        /// Subclasses may override this method to control the mapping scheme used.
        /// </summary>
        /// <param name="viewState">View state for which a visual state is desired.</param>
        /// <returns>Visual state name used to drive the
        /// <see cref="VisualStateManager"/></returns>
        /// <seealso cref="InvalidateVisualState"/>
        protected virtual string DetermineVisualState(ApplicationViewState viewState)
        {
            return viewState.ToString();
        }
    }
}